<?php

namespace app\user\controller\questionnaire\task;

use app\BaseController;
use app\model\questionnaire\QuestionnairePaperModel;
use app\model\questionnaire\QuestionnairePaperTopicModel;
use app\model\questionnaire\QuestionnaireTaskModel;
use app\model\questionnaire\QuestionnaireTaskPaperModel;
use app\model\questionnaire\QuestionnaireTaskUserModel;
use app\model\questionnaire\QuestionnaireTaskUserResultModel;
use think\App;

class Index extends BaseController
{
    public function __construct(App $app)
    {
        parent::__construct($app);
    }

    /**
     * 问卷测评任务
     * @return bool|string
     */
    public function index(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'pageSize|每页显示数量' => 'require',
            ]);
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $task_id = $QuestionnaireTaskUserModel->where([
                ['uid', '=', $this->userData['id']],
                ['is_finish', '=', 0]
            ])->column('task_id');
            $where = [];
            if (!empty($task_id)) {
                $task_id = array_unique($task_id);
                $where[] = ['id', 'in', $task_id];
            } else {
                $where[] = ['id', '=', -1];
            }
            $where[] = ['status', '=', 2];
            $QuestionnaireTaskModel = new QuestionnaireTaskModel();
            $data = $QuestionnaireTaskModel->where($where)
                ->with([
                    'user' => function ($query) {
                        $query->with(['roleName']);
                    }
                ])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['role_name'] = $item['role_name'] ?? '超级管理员';
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取任务试卷名称列表
     * @return false|string
     */
    public function getTaskPaperNameList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $data = $QuestionnaireTaskPaperModel->where('task_id', '=', $param['id'])
                ->with(['paper'])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 问卷详情
     * @return bool|string
     */
    public function paperInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            $info = $QuestionnairePaperModel->with([
                'paperTopic' => function ($query) {
                    $query->with([
                        'topic' => function ($query) {
                            $query->with(['label', 'img', 'answer']);
                        }
                    ]);
                }
            ])->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info = $info->toArray();
            $info['result_read_auth'] = explode(',', $info['result_read_auth']);
            $topic = [];
            foreach ($info['paperTopic'] as $value) {
                $value['topic']['paper_topic_id'] = $value['id'];
                $topic[] = $value['topic'];
            }
            unset($info['paperTopic']);
            $info['topic'] = $topic;
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务试卷列表
     * @return false|string
     */
    public function getTaskPaperList(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $where = [];
            $where[] = ['task_id', '=', $param['id']];
            $where[] = ['uid', '=', $this->userData['id']];
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $data = $QuestionnaireTaskUserModel->where($where)
                ->with([
                    'paper' => function ($query) {
                        $query->with(['typeName']);
                    }
                ])->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 获取任务试卷详情
     * @return false|string
     */
    public function getTaskPaperInfo(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|ID' => 'require',
            ]);
            $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
            $info = $QuestionnaireTaskUserModel->with([
                'paper' => function ($query) {
                    $query->with(['typeName']);
                },
                'task'
            ])->find($param['id']);
            if (!$info || $info['uid'] != $this->userData['id']) throw new \Exception('参数错误！');
            if ($info['is_finish'] == 1) throw new \Exception('试卷已提交，请做下张试卷！');
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 提交答案
     * @return bool|string
     */
    public function submitAnswer(): bool|string
    {
        $QuestionnaireTaskUserModel = new QuestionnaireTaskUserModel();
        $QuestionnaireTaskUserModel->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param, [
                'id|用户任务表ID' => 'require',
                'question_answer|答案' => 'require',
                'finish_used_time|用户完成用时' => 'require',
            ]);
            $info = $QuestionnaireTaskUserModel->find($param['id']);
            if (!$info || $info['uid'] != $this->userData['id']) throw new \Exception('参数错误！');
            if ($info['is_finish'] == 1) throw new \Exception('不可重复答题！');
            $QuestionnairePaperTopicModel = new QuestionnairePaperTopicModel();
            $TopicData = $QuestionnairePaperTopicModel->where('paper_id', '=', $info['paper_id'])->with([
                'topic2'
            ])->select()->toArray();
            $TopicData2 = [];
            foreach ($TopicData as $value) {
                $TopicData2[$value['topic_id']] = $value;
            }
            //得分是否有效【0否，1是】，无效说明没有计算问答题
            $param['is_valid'] = 1;
            //统计得分
            foreach ($param['question_answer'] as &$item) {
                $item['score'] = 0;
                if (empty($item['answer'])) continue;
                $topic = $TopicData2[$item['topic_id']] ?? [];
                $answer = [];
                foreach ($topic['answer'] as $v) {
                    $answer[$v['id']] = $v;
                }
                switch ($item['type']) {
                    case 1:
                        //单选
                        if ($answer[$item['answer'][0]]['status'] ?? 0 == 1) {
                            $item['score'] = $topic['score'];
                        }
                        break;
                    case 2:
                        //多选
                        $status_num = 0;
                        switch ($topic['method']) {
                            case 1:
                                foreach ($item['answer'] as $v) {
                                    if ($answer[$v]['status'] ?? 0 == 1) {
                                        $status_num++;
                                        $item['score'] = $topic['method_score'];
                                    } else {
                                        $item['score'] = 0;
                                    }
                                }
                                break;
                            case 2:
                                foreach ($item['answer'] as $v) {
                                    if ($answer[$v]['status'] ?? 0 == 1) {
                                        $status_num++;
                                        $item['score'] += $topic['method_score'];
                                    } else {
                                        $item['score'] = 0;
                                    }
                                }
                                break;
                        }
                        $status_num2 = 0;
                        foreach ($answer as $v) {
                            if ($v['status'] ?? 0 == 1) {
                                $status_num2++;
                            }
                        }
                        if ($status_num == $status_num2){
                            $item['score'] = $topic['score'];
                        }
                        break;
                    case 3:
                        //填空
                        foreach ($item['answer'] as $v) {
                            foreach ($answer as $k => $vv) {
                                if ($v == $vv['name']) {
                                    $item['score'] += $vv['score'];
                                    unset($answer[$k]);
                                }
                            }
                        }
                        break;
                    case 4:
                        //判断
                        if ($answer[$item['answer'][0]]['status'] ?? 0 == 1) {
                            $item['score'] = $topic['score'];
                        }
                        break;
                    case 5:
                        //问答
                        $param['is_valid'] = 0;
                        break;
                }
            }
            $param['total_score'] = array_sum(array_column($param['question_answer'],'score'));
            //问卷
            $QuestionnairePaperModel = new QuestionnairePaperModel();
            $PaperInfo = $QuestionnairePaperModel->find($info['paper_id']);
            if ($param['total_score'] >= $PaperInfo['pass_score']){
                $param['is_pass'] = 1;
            }else{
                $param['is_pass'] = 0;
            }
            $QuestionnaireTaskUserResultModel = new QuestionnaireTaskUserResultModel();
            $result_id = $QuestionnaireTaskUserResultModel->insertGetId([
                'unit_id' => $this->userData['unit_id'],
                'task_id' => $info['task_id'],
                'task_user_id' => $info['id'],
                'uid' => $this->userData['id'],
                'paper_id' => $info['paper_id'],
                'question_answer' => json_encode($param['question_answer'], true),
                'finish_used_time' => $param['finish_used_time'],
                'total_score' => $param['total_score'],
                'is_pass' => $param['is_pass'],
                'is_valid' => $param['is_valid'],
                'time' => time()
            ]);
            $info->save([
                'is_finish' => 1,
                'result_id' => $result_id
            ]);
            //更新任务问卷
            $QuestionnaireTaskPaperModel = new QuestionnaireTaskPaperModel();
            $QuestionnaireTaskPaperModel->where([
                ['task_id', '=', $info['task_id']],
                ['paper_id', '=', $info['paper_id']]
            ])->inc('user_complete_num')->save();
            //未完成数量
            $UnfinishedQuantity = $QuestionnaireTaskUserModel->where([
                ['task_id', '=', $info['task_id']],
                ['uid', '=', $info['uid']],
                ['is_finish', '=', 0]
            ])->count();
            if ($UnfinishedQuantity <= 1) {
                $QuestionnaireTaskModel = new QuestionnaireTaskModel();
                $TaskInfo = $QuestionnaireTaskModel->find($info['task_id']);
                //任务用户完成数加1
                $TaskInfo->user_complete_num++;
                $TaskInfo->user_complete_rate = number_format(($TaskInfo->user_complete_num / $TaskInfo->user_num) * 100, 2);
//                $TaskInfo->inc('user_complete_num');
                $TaskInfo->save();
            }
            $QuestionnaireTaskUserModel->commit();
            return success();
        } catch (\Exception $e) {
            $QuestionnaireTaskUserModel->rollback();
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

}